import { useState, useEffect } from "react";
import { TagIcon, BookOpenIcon } from "@heroicons/react/24/outline";
import { getAllTagsApi } from "../../http/module/Tags";
import { sendQuestionApi } from "../../http/module/Question";
import { getAllTopicApi } from "../../http/module/Topic";
export default function QuestionForm({ onSubmit }) {
  const [formData, setFormData] = useState({
    title: "",
    content: "",
    tags: [],
    topic: "",
  });

  // 从服务器获取标签数据
  const [availableTags, setAvailableTags] = useState([]);
  const [isLoadingTags, setIsLoadingTags] = useState(false);

  // 获取标签数据
  useEffect(() => {
    const fetchTags = async () => {
      try {
        setIsLoadingTags(true);
        // 替换为你的API调用
        const response = await getAllTagsApi();
        setAvailableTags(response.data);
      } catch (error) {
        console.error("获取标签失败:", error);
      } finally {
        setIsLoadingTags(false);
      }
    };

    fetchTags();
  }, []);
  // 获取主题数据
  const [availableTopics, setAvailableTopics] = useState([]);
  const [isLoadingTopics, setIsLoadingTopics] = useState(false);
  useEffect(() => {
    const fetchTopics = async () => {
      try {
        setIsLoadingTopics(true);
        const response = await getAllTopicApi();
        setAvailableTopics(response.data);
      } catch (error) {
        console.error("获取主题失败:", error);
      } finally {
        setIsLoadingTopics(false);
      }
    };

    fetchTopics();
  }, []);
  // 处理标签选择
  const handleTagSelect = (tagName) => {
    setFormData((prev) => ({
      ...prev,
      tags: prev.tags.includes(tagName)
        ? prev.tags.filter((name) => name !== tagName)
        : [...prev.tags, tagName],
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
  };
  // 提交问题
  const handleSendQuestion = () => {
    const payload = {
      ...formData,
      tags: formData.tags, // 直接使用存储的tag.name
    };
    sendQuestionApi(payload)
      .then((response) => {
        if (response.code === 200) {
          alert("发布问题成功");
          // 清空表单
          setFormData({
            title: "",
            content: "",
            topic: "",
            tags: [],
          });
        }
        // 处理成功逻辑
      })
      .catch((error) => {
        console.error("发布问题失败:", error);
        // 处理错误逻辑
      });
  };
  return (
    <div className="border border-gray-200 p-6 rounded-lg shadow-md bg-white">
      <form onSubmit={handleSubmit} className="space-y-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            问题标题
          </label>
          <input
            type="text"
            value={formData.title}
            onChange={(e) =>
              setFormData({ ...formData, title: e.target.value })
            }
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            placeholder="请输入清晰的问题标题"
            required
          />
        </div>
        <div>
          <label className="text-sm font-medium text-gray-700 mb-2 flex items-center">
            <BookOpenIcon className="w-5 h-5 mr-2" />
            选择主题
          </label>
          <select
            value={formData.topic} // 修正这里绑定到formData.topic
            onChange={(e) =>
              setFormData({ ...formData, topic: e.target.value })
            }
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            required
          >
            <option value="">请选择问题主题</option>
            {availableTopics.map((topic) => (
              <option key={topic.id} value={topic.name}>
                {topic.name}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className=" text-sm font-medium text-gray-700 mb-2 flex items-center">
            <TagIcon className="w-5 h-5 mr-2" />
            选择标签(最多5个)
          </label>

          {isLoadingTags ? (
            <div className="flex items-center text-gray-500">
              <svg className="animate-spin h-5 w-5 mr-2" viewBox="0 0 24 24">
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                  fill="none"
                />
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
              加载标签中...
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
              {availableTags.map((tag) => (
                <button
                  type="button"
                  key={tag.id}
                  onClick={() => handleTagSelect(tag.name)}
                  className={`px-3 py-1.5 text-sm rounded-full border transition-colors
      ${
        formData.tags.includes(tag.name) // 改为检查tag.name
          ? "bg-blue-100 border-blue-300 text-blue-700"
          : "bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100"
      }`}
                  disabled={
                    formData.tags.length >= 5 &&
                    !formData.tags.includes(tag.name)
                  }
                >
                  {tag.name}
                </button>
              ))}
            </div>
          )}

          <div className="mt-2 text-sm text-gray-500">
            已选择 {formData.tags.length} 个标签
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            详细描述
          </label>
          <textarea
            value={formData.content}
            onChange={(e) =>
              setFormData({ ...formData, content: e.target.value })
            }
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 h-40"
            placeholder="请详细描述您的问题（支持Markdown语法）"
            required
          />
        </div>
        {/* 提交按钮 */}
        <button
          type="submit"
          onClick={handleSendQuestion}
          className="w-full py-3 px-4 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
        >
          发布问题
        </button>
      </form>
    </div>
  );
}
